//
//  ARRessume.m
//  ARWebImage
//
//  Created by 包日守 on 15/11/6.
//  Copyright © 2015年 Arise. All rights reserved.
//

#import "ARRessume.h"
#import "NSString+MD5Addition.h"

@interface ARRessume ()<NSURLSessionDownloadDelegate>
@property (nonatomic) NSURLSessionDownloadTask *task;
@property (nonatomic) NSURLSession *session;

@property (nonatomic) NSMutableURLRequest *request;
@property (nonatomic) NSNumber *downloadSize;

@property (nonatomic) NSData * resumeData;

@end

@implementation ARRessume


- (NSURLSession *) session
{
    if (!_session) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (NSString *) localPath
{
    NSString *path = NSHomeDirectory();
    NSString *fileName = [_stringURL stringFromMD5];
    path = [path stringByAppendingFormat:@"/Documents/ARRessumeTemp/%@",fileName];
    return path;

}

- (NSString *) localFilesPath
{
    NSString *path = NSHomeDirectory();
    path = [path stringByAppendingFormat:@"/Documents/ARRessumeTemp"];
    return path;

}



- (void) startDownload
{
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self localPath]]) {
        if (self.success) {
            self.success([NSData dataWithContentsOfFile:self.localPath]);
        }

    }
    else
    {
        if (self.resumeData) {
            self.task = [self.session downloadTaskWithResumeData:self.resumeData];
            
        }
        else{
            self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:self.stringURL]];
        }
        
        [self.task resume];
        
        self.resumeData = nil;

    
    }
    
    
}



- (void) pauseDownLoad
{
    __weak typeof(self) vc = self;
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        
        self.resumeData = resumeData;
        vc.task = nil;
        
    }];
    
}




+ (void) removeAllTemp
{
    
    NSString *extension = @"";
   // NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *docDirPath = NSHomeDirectory();
    docDirPath = [docDirPath stringByAppendingFormat:@"/Documents"];
    
    NSString *filesPath = [NSString stringWithFormat:@"%@/ARRessumeTemp",docDirPath];
    
    NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filesPath error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        
        if ([[filename pathExtension] isEqualToString:extension]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:[filesPath stringByAppendingPathComponent:filename] error:NULL];
        }
    }
    
    
}


#pragma mark - sessionDelegate

- (void) URLSession:(NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    
 
    if (self.loadingData) {
        self.loadingData([NSNumber numberWithLongLong:totalBytesWritten],[NSNumber numberWithLongLong:totalBytesExpectedToWrite]);
    }
    

}

- (void) URLSession:(NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location
{
    
    NSData *data = [NSData dataWithContentsOfURL:location];
 
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self localFilesPath]]) {
         [[NSFileManager defaultManager] createDirectoryAtURL:[NSURL fileURLWithPath:[self localFilesPath]] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    [data writeToFile:self.localPath atomically:YES];
    
    if (self.success) {
        self.success(data);
    }

}

/*
- (NSString *) getLastFile
{
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *rootPath = [paths objectAtIndex:0];//获取根目录
    
    
    NSString *filepath = [NSHomeDirectory() stringByAppendingFormat:@"/tmp"];
    
    paths = [fileMgr subpathsAtPath:filepath];//取得文件列表
    NSArray *sortedPaths = [paths sortedArrayUsingComparator:^(NSString * firstPath, NSString* secondPath) {//
        NSString *firstUrl = [rootPath stringByAppendingPathComponent:firstPath];//获取前一个文件完整路径
        NSString *secondUrl = [rootPath stringByAppendingPathComponent:secondPath];//获取后一个文件完整路径
        NSDictionary *firstFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:firstUrl error:nil];//获取前一个文件信息
        NSDictionary *secondFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:secondUrl error:nil];//获取后一个文件信息
        id firstData = [firstFileInfo objectForKey:NSFileModificationDate];//获取前一个文件修改时间
        id secondData = [secondFileInfo objectForKey:NSFileModificationDate];//获取后一个文件修改时间
        //return [firstData compare:secondData];//升序
         return [secondData compare:firstData];//降序
    }];

    return [sortedPaths lastObject];

}
*/
/*
<code class="hljs objectivec">NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *rootPath = [paths objectAtIndex:0];//获取根目录
NSArray *paths = [fileMgr subpathsAtPath:rootPath];//取得文件列表
NSArray *sortedPaths = [paths sortedArrayUsingComparator:^(NSString * firstPath, NSString* secondPath) {//
    NSString *firstUrl = [rootPath stringByAppendingPathComponent:firstPath];//获取前一个文件完整路径
    NSString *secondUrl = [rootPath stringByAppendingPathComponent:secondPath];//获取后一个文件完整路径
    NSDictionary *firstFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:firstUrl error:nil];//获取前一个文件信息
    NSDictionary *secondFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:secondUrl error:nil];//获取后一个文件信息
    id firstData = [firstFileInfo objectForKey:NSFileModificationDate];//获取前一个文件修改时间
    id secondData = [secondFileInfo objectForKey:NSFileModificationDate];//获取后一个文件修改时间
    return [firstData compare:secondData];//升序
    // return [secondData compare:firstData];//降序
}];
</code>

*/
@end
